package webapp

import (
	"github.com/gin-gonic/gin"
	"time"
	"yundian/internel/pkg/dingo/global"

	"yundian/internel/app/dao"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/logic"
	"yundian/internel/app/models/goods"
	"yundian/internel/app/models/paysetting"
	"yundian/internel/app/models/room"
	"yundian/internel/pkg/dingo"
	. "yundian/internel/pkg/dingo/result"
)

func HandleGetAutomatePdPassword(c *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(c)
	dingo.ErrorIf(err).Unwrap()

	param := &request.GetAutomatePdPasswordReq{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	param.LoginUserId = userId

	pwd := logic.NewDeviceLogic().HandleGetAutomatePasswordReplenish(param.DeviceSn, 1440)

	Response(c)("", CodeSuccess, map[string]interface{}{
		"password": pwd,
	})(OK)
	return
}

// HandleStewardWebAppLoginBind 小程序登录绑定 公众号openid
func HandleStewardWebAppLoginBind(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.AppSetUserInfoReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.LoginUserId = userId
	param.UpdateTime = time.Now().Format("2006-01-02 15:04:05")

	data := dao.NewUsersStaffDao().SetUserInfo(param)
	Response(ctx)("", CodeSuccess, data.Err == nil)(OK)
}

func HandleSetRoomOrderStatus(ctx *gin.Context) {
	param := &request.StewardSetDataReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	param.LoginUserId, _ = helper.GetUserIdFromCtx(ctx)

	data := dao.NewRoomDaoDao().GetH5RoomOrdersInfo(param).Unwrap().(*room.Order)
	if data.Id <= 0 {
		Response(ctx)("", CodeInvalidParam, false)(OK)
		return
	}

	// 执行退款
	if data.Status != helper.TypeNumRoomOrderStatusRepeal && data.PayType == 1 && param.RoomOrderStatus == helper.TypeNumRoomOrderStatusRepeal {
		if err := logic.NewOrderLogic().HandleWxStewardCancelOrder(&paysetting.WxStewardCancelOrder{PathKey: "room",
			TransactionId: data.ThirdTradeNo, TradeNo: data.TradeNo, Amount: int64(data.Amount)}); err != nil {
			Response(ctx)("", CodeInvalidParam, false)(OK)
			return
		}
	}

	if dao.NewRoomDaoDao().SetH5RoomOrdersStatus(data, param).Err != nil {
		Response(ctx)("", CodeInvalidParam, false)(OK)
		return
	}

	Response(ctx)("", CodeSuccess, true)(OK)
}

// HandleGetRoomOrderDetails HandleGetGoodsOrderDetails 查询订单详情
func HandleGetRoomOrderDetails(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	param := &request.GetH5StewardRoomOrderDetailsReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.StaffId = userId

	data := &request.GetH5StewardRoomOrderDetailsRes{}
	orderList := dao.NewRoomDaoDao().GetAdminRoomOrdersByNotificationIds([]int{param.NotificationId}).Unwrap().([]*room.Order)
	if len(orderList) > 0 {
		data.Id = orderList[0].Id
		data.Amount = orderList[0].Amount
		data.DayLen = orderList[0].DayLen
		data.TradeNo = orderList[0].TradeNo
		data.PayType = orderList[0].PayType
		data.MemberName = orderList[0].MemberName
		data.MemberPhone = orderList[0].MemberPhone
	}

	Response(ctx)("", CodeSuccess, map[string]interface{}{
		"host": global.Cfg.Ali.AliossPath,
		"data": data,
	})(OK)
}

// HandleGetGoodsOrderDetails 查询订单详情
func HandleGetGoodsOrderDetails(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	param := &request.GetH5StewardGoodsOrderDetailsReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.StaffId = userId

	data := dao.NewGoodsDao().GetH5GoodsOrdersDetailsReq(param)
	Response(ctx)("", CodeSuccess, map[string]interface{}{
		"host": global.Cfg.Ali.AliossPath,
		"data": data.Unwrap(),
	})(OK)
}

func HandleUpdateAutomateGoodsBindStatus(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.HandleUpdateAutomateGoodsBindStatusReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.LoginUserId, _ = helper.GetUserIdFromCtx(ctx)
	param.IsAdmin, _ = helper.GetIsAdminFromCtx(ctx)

	if data := dao.NewAutomateDaoDao().UpdateGoodsBindStatusByDeviceSn(param); data.Err != nil {
		Response(ctx)("", CodeInternalServerError, nil)(OK)
		return
	}

	nParam := &request.StewardSetDataReq{
		NotificationId: param.NotificationId,
		ServiceMessage: param.ServiceMessage,
		Status:         helper.TypeNumNotificationStatusFinish,
	}
	nParam.LoginUserId = userId
	if data := dao.NewNotificationDaoDao().SetNotificationServiceData(nParam); data.Err != nil {
		Response(ctx)("", CodeSuccess, false)(OK)
		return
	}

	Response(ctx)("", CodeSuccess, true)(OK)
}

func HandleGetAutomateOrdersDetails(c *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(c)
	dingo.ErrorIf(err).Unwrap()

	param := &request.GetStaffAutomateOrdersDetailsReq{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	param.LoginUserId = userId

	data := dao.NewAutomateDaoDao().GetStaffAutomateOrdersDetails(param)
	Response(c)("", CodeSuccess, map[string]interface{}{
		"data": data.Unwrap(),
		"host": global.Cfg.Ali.AliossPath,
	})(OK)
	return
}

func HandleCommentDetails(c *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(c)
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	param := &request.CommentInfoReq{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	//param.MemberId = 1
	param.MemberId = userId

	commentInfoDetails := dao.NewNotificationDaoDao().GetH5CommentDetails(param).Unwrap().(*request.CommentDetailsInfoRes)
	commentInfoDetails.PlaceAddress = commentInfoDetails.Province + commentInfoDetails.City + commentInfoDetails.County + commentInfoDetails.PlaceAddress

	Response(c)("", CodeSuccess, map[string]interface{}{
		"data": commentInfoDetails,
		"host": global.Cfg.Ali.AliossPath,
	})(OK)
	return
}

// HandleStewardUserLogin 员工登录
func HandleStewardUserLogin(ctx *gin.Context) {
	param := &struct {
		UserName string `json:"username"`
		UserPwd  string `json:"password"`
		Openid   string `json:"openid"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	var loginInfo *request.LoginBack
	var err error

	loginInfo, err = logic.NewStewardLogic().UserLoginBySteward(param.UserName, param.UserPwd, param.Openid, ctx.ClientIP())
	if err != nil {
		Response(ctx)(err.Error(), CodeSuccess, loginInfo)(OK)
		return
	}

	// 响应请求
	Response(ctx)("登录成功", CodeSuccess, loginInfo)(OK)
}

// HandleStewardUserStaffAppLogin HandleStewardUserLogin 员工登录
func HandleStewardUserStaffAppLogin(ctx *gin.Context) {
	param := &struct {
		UserName string `json:"username"`
		UserPwd  string `json:"password"`
		Openid   string `json:"openid"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	var loginInfo *request.LoginBack
	var err error

	loginInfo, err = logic.NewStewardLogic().UserLoginByStewardApp(param.UserName, param.UserPwd, param.Openid, ctx.ClientIP())
	if err != nil {
		Response(ctx)(err.Error(), CodeInternalServerError, loginInfo)(OK)
		return
	}

	// 响应请求
	Response(ctx)("登录成功", CodeSuccess, loginInfo)(OK)
}

// HandleStewardGetList 查询服务列表
func HandleStewardGetList(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.NotificationListReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.LoginUserId = userId

	data := dao.NewNotificationDaoDao().GetH5NotificationServiceListByStaffId(param)
	NotificationList := data.Unwrap().([]*request.NotificationListRes)

	var notificationIds []int
	for _, item := range NotificationList {
		notificationIds = append(notificationIds, item.Id)
	}
	if len(notificationIds) > 0 {
		goodsList := dao.NewGoodsDao().GetGoodsListByNotificationIds(notificationIds).Unwrap().([]*request.NotificationListRes)
		for _, item := range NotificationList {
			for _, goodsItem := range goodsList {
				if item.Id == goodsItem.Id {
					item.GoodsId = goodsItem.GoodsId
					item.GoodsName = goodsItem.GoodsName
					item.CommentId = goodsItem.CommentId
					break
				}
			}
		}
	}

	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       data.Unwrap(),
	})(OK)
}

// HandleStewardGetDetails 查询服务详情
func HandleStewardGetDetails(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.StewardGetDetailsReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.LoginUserId = userId

	data := dao.NewNotificationDaoDao().GetNotificationServiceDetailsByStaffId(param)
	Response(ctx)("", CodeSuccess, data.Unwrap())(OK)
}

// HandleStewardSetGoodsOrderData 服务操作人/状态设置
func HandleStewardSetGoodsOrderData(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.StewardSetDataReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	param.IsAdmin, _ = helper.GetIsAdminFromCtx(ctx)
	param.LoginUserId = userId
	param.ParentId, _ = helper.GetParentIdFromCtx(ctx)

	data := dao.NewGoodsDao().GetH5GoodsOrdersInfo(param).Unwrap().(*goods.Orders)
	if data.Id <= 0 {
		Response(ctx)("", CodeInvalidParam, false)(OK)
		return
	}

	// 执行退款
	if data.Status != helper.TypeNumNotificationStatusFinish && param.GoodsOrderStatus == helper.TypeNumGoodsOrderStatusRepeal {
		if err := logic.NewOrderLogic().HandleWxStewardCancelOrder(&paysetting.WxStewardCancelOrder{
			TransactionId: data.ThirdTradeNo, TradeNo: data.TradeNo, Amount: int64(data.Amount)}); err != nil {
			Response(ctx)("", CodeInvalidParam, false)(OK)
			return
		}
	}

	param.NotificationId = data.NotificationId
	param.Status = helper.TypeNumNotificationStatusFinish
	if dao.NewNotificationDaoDao().SetNotificationServiceData(param).Err != nil {
		Response(ctx)("", CodeInvalidParam, false)(OK)
		return
	}

	goodsParams := &request.SetGoodsOrderStatusReq{
		TradeNo:        data.TradeNo,
		RejectMessage:  param.ServiceMessage,
		NotificationId: data.NotificationId,
		Status:         param.GoodsOrderStatus,
		IsAdmin:        helper.TypeNumIsAdminOperator,
	}
	if dao.NewGoodsDao().SetAdminGoodsOrdersStatus(data, goodsParams).Err != nil {
		Response(ctx)("", CodeInvalidParam, false)(OK)
		return
	}
	Response(ctx)("", CodeSuccess, userId)(OK)
}

// HandleStewardSetData 服务操作人/状态设置
func HandleStewardSetData(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.StewardSetDataReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.LoginUserId = userId

	if data := dao.NewNotificationDaoDao().SetNotificationServiceData(param); data.Err != nil {
		Response(ctx)("", CodeSuccess, false)(OK)
		return
	}
	Response(ctx)("", CodeSuccess, userId)(OK)
}

func HandleStewardStaffGetDetails(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.StStaffListReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.LoginUserId = userId

	data := dao.NewUserDao().GetStewardStaffUserInfo(param)
	Response(ctx)("", CodeSuccess, data.Unwrap())(OK)
}
